<div class="row">
    <div class="col-lg-12">
        <section class="panel">
            <header class="panel-heading">
                文件列表
            </header>
            <div class="panel-body">

                <div class="row">
                    <div class="col-lg-6 col-md-12">
                        <form class="form-inline" role="form" onsubmit="return false;">
                            <div class="form-group">
                                <input type="text" class="form-control" id="Keyword" placeholder="请输入文件名">
                            </div>
                            <button id="SearchBtn" type="button" class="btn btn-success">搜索</button>
                            <button id="ResetBtn" type="button" class="btn btn-danger">重置</button>
                        </form>
                    </div>
                </div>

                <div class="row">
                    <div class="col-lg-12">
                        <table id="DataList" lay-filter="DataList" class="table"></table>
                        <!-- 头工具栏 -->
                        <script type="text/html" id="HeadToolBar">
                            <div class="layui-btn-container">
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="groupMgr">
                                    <i class="icon-folder-open-alt"></i> 分组管理
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="uploadFile">
                                    <i class="icon-file-alt"></i> 上传文件
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary " lay-event="delete">
                                    <i class="icon-trash"></i> 删除选中
                                </button>
                            </div>
                        </script>
                        <!-- 行工具栏 -->
                        <script type="text/html" id="ToolBar">
                            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</a>
                        </script>
                        <!-- 文件栏模板 -->
                        <script type="text/html" id="FileUrlTpl">
                            {{# var IconSrc = mb_GetFileIcon(d.FileUrl); }}
                            <a href="{{d.FileUrl}}" target="_blank"><img src="{{IconSrc}}" height="40px"></a>
                        </script>
                    </div>
                </div>
            </div>
        </section>

    </div>
</div>
<!-- 分組管理对话框 -->
<div id="GroupMgrDialog" style="display: none; ">
    <div style="padding: 10px">

        <form class="form-inline" role="form" onsubmit="return false;">
            <div class="form-group">
                <input type="text" class="form-control" id="GroupName" placeholder="请输入分组名">
            </div>
            <button id="AddGroupBtn" type="button" class="btn btn-success">添加</button>
        </form>

        <table id="GroupList" lay-filter="GroupList" class="table"></table>
        <!-- 行工具栏 -->
        <script type="text/html" id="GroupToolBar">
            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</a>
        </script>
    </div>
</div>
<!-- 上传文件对话框 -->
<div id="UploadFileDialog" style="display: none;">
    <form class="form-horizontal" role="form">
        <div class="row" style="margin: 15px 15px;">
            <div class="form-group">
                <label class="col-md-3 control-label">文件名</label>
                <div class="col-md-9">
                    <input id="Name" type="text" class="form-control" placeholder="">
                </div>
            </div>
            <div class="form-group ">
                <label class="col-md-3 control-label">分组</label>
                <div class="col-md-9">
                    <select id="GroupID" class="form-control m-bot15">
                        <option value="0">无</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">备注</label>
                <div class="col-md-9">
                    <textarea id="Remark" class="form-control"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-3 control-label">文件</label>
                <div class="col-md-9">
                    <div class="row">
                        <div class="col-lg-9">
                            <input id="OpenFileName" type="text" class="form-control" placeholder="" readonly>
                        </div>
                        <div class="col-lg-3">
                            <button type="button" class="btn btn-danger" id="OpenFileBtn">选择文件</button>
                            <input type="file" id="OpenFile" style="display: none">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
    layui.use(['table', 'layer', 'jquery', 'upload', 'laydate'], function () {
        var table = layui.table,
            layer = layui.layer,
            upload = layui.upload,
            laydate = layui.laydate,
            $ = layui.$

        //文件数据表格实例
        var tableIns = table.render({
            elem: '#DataList'
            , height: '690'
            , url: '/index.php/user/Contract/mb_FileListing' //数据接口
            , page: {
                theme: '#ff6c60'
            }
            , toolbar: '#HeadToolBar' //开启头部工具栏，并为其绑定左侧模板
            , limit: 100
            , limits: [100, 200, 300, 400, 500]
            , cols: [[ //表头 總寬度1670
                {type: 'checkbox', fixed: 'left'}
                , {field: 'Name', title: '文件名', width: 200, fixed: 'left'}
                , {field: 'GroupName', title: '分组名',sort: true}
                , {field: 'Remark', title: '备注'}
                , {field: 'FileUrl', title: '文件', width: 160, templet: '#FileUrlTpl'}
                , {field: 'TimeCreated', title: '创建时间', width: 200, sort: true}
                , {title: '編輯', width: 80, align: 'center', toolbar: '#ToolBar', fixed: 'right'}
            ]]
        });

        //触发排序事件
        table.on('sort(DataList)', function (obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            table.reload('DataList', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    Keyword: $('#Keyword').val(),
                    OrderField: obj.field, //排序字段
                    OrderType: obj.type //排序方式
                }
            });
        });

        //头工具栏事件
        table.on('toolbar(DataList)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'groupMgr':
                    //分组管理
                    var dialogWidth = '650px';
                    if (document.documentElement.scrollWidth < 500) {
                        //手機版
                        dialogWidth = '350px';
                    }
                    layer.open({
                        type: 1,
                        title: '分组管理',
                        area: [dialogWidth, '700px'],
                        content: $('#GroupMgrDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                    break;
                case 'uploadFile':
                    //请求分组列表
                    $('#GroupID').empty();
                    var fields = {
                        page:1,
                        limit:9999999,
                    }
                    global.post('/index.php/user/Contract/mb_GroupListing', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            $("#GroupID").append("<option value='0'>无</option>");
                            for (var i = 0; i < msg['data'].length; i++) {
                                var data = msg['data'][i];
                                $("#GroupID").append("<option value='"+data.ID+"'>"+data.Name+"</option>");
                            }
                        } else mb_OnMessage(msg);
                    });

                    $('#Name').val('');
                    $('#Remark').val('');
                    $('#OpenFileName').val('');
                    $('#file').val('');

                    //弹出对话框
                    var dialogWidth = '650px';
                    if (document.documentElement.scrollWidth < 500) {
                        //手機版
                        dialogWidth = '350px';
                    }
                    layer.open({
                        type: 1,
                        title: '上传文件',
                        area: [dialogWidth, '380px'],
                        content: $('#UploadFileDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        btn:['确定','取消'],
                        yes: function (index, layero) {
                            var Name = $('#Name').val();
                            var Remark = $('#Remark').val();
                            var OpenFileName = $('#OpenFileName').val();

                            if(Name == ''){
                                layer.msg('请输入文件名');
                                return false;
                            }
                            if(OpenFileName == ''){
                                layer.msg('请选择文件');
                                return false;
                            }

                            var obj = document.getElementById('OpenFile').files;
                            var formData = new FormData();
                            formData.append('File', obj[0]);
                            //上传文件
                            $.ajax({
                                type: "POST",
                                url: "/index.php/index/Common/UploadFile",  //上傳接口
                                dataType: "json",
                                data: formData,
                                // 不处理发送的数据
                                processData: false,
                                // 不设置Content-Type请求头
                                contentType: false,
                                async: true,
                                success: function (msg) {
                                    //上传
                                    if (msg['code'] == ErrCode_Normal) {
                                        var FileUrl = msg['data']['src'];
                                        var fields = {
                                            GroupID: $('#GroupID').val(),
                                            Name: Name,
                                            Remark:Remark,
                                            FileUrl:FileUrl
                                        };
                                        global.post('/index.php/user/Contract/mb_AddFile', fields, function (msg) {
                                            if (msg['code'] == ErrCode_Normal) {
                                                layer.msg(msg['msg'], {
                                                    offset: '15px'
                                                    , icon: 1
                                                    , time: 1000
                                                }, function () {
                                                    tableIns.reload();
                                                    layer.close(index);
                                                });
                                            } else mb_OnMessage(msg);
                                        });
                                    } else mb_OnMessage(msg);
                                },
                                complete: function () {

                                }
                            });




                        },
                        btn2: function (index, layero) {

                        }
                    });
                    break;
                case 'delete':
                    //刪除選中
                    if (checkStatus.data.length == 0) {
                        layer.msg('请选择文件', {icon: 2});
                        return false
                    }
                    var data = checkStatus.data;
                    var ids = '';
                    for (var i = 0; i < data.length; i++) {
                        ids += data[i].ID;
                        if (i != data.length - 1) ids += ','
                    }
                    var fields = {
                        Type: 'CompanyFile',
                        IDs: ids
                    };
                    global.post('/index.php/user/Event/mb_Delete', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg(msg['msg'], {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                tableIns.reload();
                            });
                        } else mb_OnMessage(msg);
                    });
                    break;
                default:
                    break;
            }
        });

        //监听行工具事件
        table.on('tool(DataList)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if (layEvent === 'del') {
                //删除记录
                var fields = {
                    Type: 'CompanyFile',
                    IDs: data.ID
                };
                global.post('/index.php/user/Event/mb_Delete', fields, function (msg) {
                    if (msg['code'] == ErrCode_Normal) {
                        layer.msg(msg['msg'], {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {
                            obj.del();//删除行
                        });
                    } else mb_OnMessage(msg);
                });
            }
        });
        //分组数据表格初始化
        var groupTable = table.render({
            elem: '#GroupList'
            , autoSort: false   //禁用自動排序
            , height: '565'
            , url: '/index.php/user/Contract/mb_GroupListing' //数据接口
            , page: {
                theme: '#ff6c60'
            }
            , limit: 100
            , limits: [100, 200, 300, 400, 500]
            , cols: [[ //表头 總寬度1670
                {field: 'Name', title: '分组名'}
                , {field: 'TimeCreated', title: '创建时间', sort: true}
                , {title: '編輯', width: 100, align: 'center', toolbar: '#GroupToolBar'}
            ]]
        });

        //新增分组按钮按下
        $('#AddGroupBtn').bind('click', function () {
            var GroupName = $('#GroupName').val();
            if(GroupName == ''){
                layer.msg('请输入分组名');
                return false;
            }
            var fields = {
                Name : GroupName
            }
            global.post('/index.php/user/Contract/mb_AddGroup', fields, function (msg) {
                if (msg['code'] == ErrCode_Normal) {
                    layer.msg(msg['msg'], {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    }, function () {
                        groupTable.reload();
                    });
                } else mb_OnMessage(msg);
            });
        });
        //上传文件-选择文件按钮按下
        $('#OpenFileBtn').bind('click', function () {
            $('#OpenFile').click();
        });
        //打开文件回调
        $("#OpenFile").change(function () {
            var obj = this.files;
            var abn = obj[0].name;
            var lastname = abn.substring(abn.lastIndexOf(".")).toLowerCase();
            // if (!(lastname == ".xls" || lastname == ".xlsx")) {
            //     layer.msg('请选择Excel文件');
            //     return;
            // }
            $('#OpenFileName').val(abn);
        })
    });



</script>
<style>
    .layui-input {
        border-color: #e2e2e4;
        height: 34px;
        border-radius: 4px;
        color: #c2c2c2;
    }

    .xsg-span-required {
        color: red;
        margin: 0 5px;
    }

    .layui-table-tips-c:before {
        position: relative;
        right: 1px;
        top: -3px;
    }
    .layui-table-cell{
        height:50px;
        line-height: 50px;
    }
</style>